import datetime
import threading
import time

from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.schedulers.blocking import BlockingScheduler
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views.decorators.csrf import csrf_exempt

from PythonWebTools import settings
from countdata import models
from countdata.countcjdata import Countcjsqldata
from countdata.countjgdata import Countjgsqldata
from django_apscheduler.jobstores import DjangoJobStore, register_job, logger

from countdata.countjgdata_country import Countjgsqldatacountry

from django.db import connection


def is_connection_usable():
    try:
        connection.connection.ping()
    except:
        return False
    else:
        return True


def do_work():  # 每秒检查一次数据库连接
    print("%s:检查数据库连接" % datetime.datetime.now())
    if not is_connection_usable():
        connection.close()
    # while (True):  # Endless loop that keeps the worker going (simplified)
    #     print("检查数据库连接")
    #     if not is_connection_usable():
    #         connection.close()
    #     try:
    #         pass
    #     except:
    #         logger.exception("Something bad happened, trying again")
    #         time.sleep(1)

@csrf_exempt
def countcjdata(request):
    while (True):  # Endless loop that keeps the worker going (simplified)
        print("检查数据库连接")
        if not is_connection_usable():
            connection.close()
        try:
            # 获取最近日期统计的数据
            date_now = datetime.date.today()
            cj_count_list = models.cjdata.objects.filter(count_date=date_now).values()
            # 如果获取的数据条数少于20条则当天数据未统计完毕
            while len(cj_count_list) < 20:
                date_now = date_now + datetime.timedelta(days=-1)
                cj_count_list = models.cjdata.objects.filter(count_date=date_now).values()
            cj_count_list = list(cj_count_list)
            return render(request, 'showcjdata.html', {"cj_count_list": cj_count_list})
        except:
            logger.exception("Something bad happened, trying again")
            time.sleep(1)


@csrf_exempt
def countjgdata(request):
    while (True):  # Endless loop that keeps the worker going (simplified)
        print("检查数据库连接")
        if not is_connection_usable():
            connection.close()
        try:
            # 获取最近日期统计的数据
            date_now = datetime.date.today()
            jg_count_list = models.jgdata.objects.filter(count_date=date_now).values()
            # 如果获取的数据条数少于20条则当天数据未统计完毕
            while len(jg_count_list) < 20:
                date_now = date_now + datetime.timedelta(days=-1)
                jg_count_list = models.jgdata.objects.filter(count_date=date_now).values()
            jg_count_list = list(jg_count_list)
            return render(request, 'showjgdata.html', {"jg_count_list": jg_count_list})
        except:
            logger.exception("Something bad happened, trying again")
            time.sleep(1)


@csrf_exempt
def countjgcydata(request):
    while (True):  # Endless loop that keeps the worker going (simplified)
        print("检查数据库连接")
        if not is_connection_usable():
            connection.close()
        try:
            # 获取最近日期统计的数据
            date_now = datetime.date.today()
            jg_count_list = models.jgdata_country.objects.filter(count_date=date_now).values()
            # 如果获取的数据条数少于20条则当天数据未统计完毕
            while len(jg_count_list) < 20:
                date_now = date_now + datetime.timedelta(days=-1)
                jg_count_list = models.jgdata_country.objects.filter(count_date=date_now).values()
            jg_count_list = list(jg_count_list)
            return render(request, 'showjgcydata.html', {"jg_count_list": jg_count_list})
        except:
            logger.exception("Something bad happened, trying again")
            time.sleep(1)


def countdata():
    print("%s数据统计开始" % datetime.datetime.now())
    thread_list = []
    thread1 = threading.Thread(target=Countcjsqldata().countvalue)
    thread2 = threading.Thread(target=Countjgsqldata().countvalue)
    thread3 = threading.Thread(target=Countjgsqldatacountry().countvalue)
    thread_list.append(thread1)
    thread_list.append(thread2)
    thread_list.append(thread3)
    for t in thread_list:
        t.setDaemon(True)
        t.start()
    for i in thread_list:
        i.join()
    print("%s数据统计结束" % datetime.datetime.now())
# 定时任务
# try:
#     # 设置最大线程数为3
#     job_defaults = {'max_instances': 3}
#     scheduler = BackgroundScheduler(timezone=settings.TIME_ZONE, job_defaults=job_defaults)
#     # scheduler = BackgroundScheduler()
#     scheduler.add_jobstore(DjangoJobStore(), "default")
#
#
#     @register_job(scheduler, 'cron', hour="23", minute = "59", id="task_data")
#     def countdata():
#         """
#         每天晚上11:59定时执行采集数据和加工数据统计程序
#         :return:
#         """
#         print("%s数据统计开始" % datetime.datetime.now())
#         thread_list = []
#         thread1 = threading.Thread(target=Countcjsqldata().countvalue)
#         thread2 = threading.Thread(target=Countjgsqldata().countvalue)
#         thread3 = threading.Thread(target=Countjgsqldatacountry().countvalue)
#         thread_list.append(thread1)
#         thread_list.append(thread2)
#         thread_list.append(thread3)
#         for t in thread_list:
#             t.setDaemon(True)
#             t.start()
#         for i in thread_list:
#             i.join()
#         print("%s数据统计结束" % datetime.datetime.now())
#
#     # register_events(scheduler)
#     scheduler.start()
#     print("采集加工数据量统计定时任务启动!")
# except Exception as e:
#     print("定时服务错误,已关闭:%s" % e)
#     # 有错误就停止定时器
#     scheduler.shutdown()
#
countdata()
scheduler1 = BackgroundScheduler()
scheduler1.add_job(countdata, 'cron', hour="23", minute = "59")    # 每半小时检查一次数据库连接
print("采集加工数据量统计定时任务启动")
scheduler1.start()
